package com.monitor.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.monitor.commons.NumberUtil;
import com.monitor.commons.SecurityUtil;
import com.monitor.commons.SkList;
import com.monitor.commons.StringUtil;
import com.monitor.commons.enums.WhetherEnum;
import com.monitor.commons.redis.RedisUtil;
import com.monitor.dao.IAdminDao;
import com.monitor.exception.ExceptionMessage;
import com.monitor.model.Rights;
import com.monitor.modelExt.AdminExt;
import com.monitor.modelExt.RightsExt;
import com.monitor.pubInter.AbstractBaseService;
import com.monitor.pubInter.BaseSearch;
import com.monitor.pubInter.IBaseDao;
import com.monitor.pubInter.exception.BusinessException;
import com.monitor.pubInter.exception.SkException;
import com.monitor.searchExt.AdminSearchExt;
import com.monitor.searchExt.RightsSearchExt;
import com.monitor.service.IAdminPermissionGroupService;
import com.monitor.service.IAdminService;
import com.monitor.service.IGroupRightsService;
import com.monitor.service.IRightsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
*    @author afeng
*    @Date 2025-03-17 10:50:13
*    @description AdminService      系统用户
*/
@Service(value = "adminService")
@Slf4j
public class AdminServiceImpl extends AbstractBaseService<AdminExt, AdminSearchExt,String> implements IAdminService {

    @Resource(name = "adminDao")
    private IAdminDao adminDao;

    @Resource
    private IAdminPermissionGroupService adminPermissionGroupService;
    @Resource
    private IGroupRightsService groupRightsService;
    @Resource
    private RedisUtil redisUtil;
    @Resource(name = "rightsService")
    private IRightsService rightsService;//权限

    @Override
    public IBaseDao<AdminExt, AdminSearchExt,String> getDao() {
        return adminDao;
    }






    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     * @throws SkException
     */
    @Override
    public AdminExt loginByUsernameAndPsw(String username, String password) throws SkException {

        if (StringUtil.isNullOrEmpty(username)) {
            throw new BusinessException(ExceptionMessage.EXIST_NO_CLIENT);
        }

        AdminExt admin = getInfoByUsername(username);

        if (StringUtil.isNullOrEmpty(admin)) {
            throw new BusinessException(ExceptionMessage.EXIST_NO_CLIENT);
        }
        password = SecurityUtil.generateUserPasswordByPswAndSalt(password, admin.getId());
        if (!admin.getPassword().equalsIgnoreCase(password)) {
            throw new BusinessException(ExceptionMessage.PSW_ERROR);
        }
        int locking = NumberUtil.parseInt(admin.getForbidden());
        if (locking == WhetherEnum.YES.getValue()) {
            throw new BusinessException(ExceptionMessage.LOCK);
        }
        return admin;


    }

    /**
     * 得到一个所有权限
     *
     * @param staffId
     * @return
     */
    @Override
    public List<String> getAllRightsIdsByStaffId(String staffId) {

        List<String> rightsIds = null;
        List<String> allRightsIds = SkList.getInstance();

        //自定义权限组的
        rightsIds = groupRightsService.getRightsIdsByStaffId(staffId);


        if (StringUtil.isNotObjEmpty(rightsIds)) {
            allRightsIds.addAll(rightsIds);
        }


        return allRightsIds;
    }

    /**
     * 根据用户名得到员工详情
     *
     * @param username
     * @return
     */
    @Override
    public AdminExt getInfoByUsername(String username) {
        if (StringUtil.isNullOrEmpty(username)) {
            return null;
        }

        return getDetailBySearch(AdminSearchExt.getInstance().setUsernameEq(username));
    }

    /**
     * 根据手机号码查询
     *
     * @param phone
     * @return
     */
    @Override
    public AdminExt getInfoByPhone(String phone) {

        if (StringUtil.isNullOrEmpty(phone)) {
            return null;
        }


        return getDetailBySearch(AdminSearchExt.getInstance().setPhoneEq(phone));
    }

    @Override
    public List<RightsExt> getAllRightsListByStaffId(String staffId, boolean cache) {
        try {

            if (cache) {
                List<Object> allList = redisUtil.lGet(staffId);
                if (StringUtil.isNotObjEmpty(allList)) {
                    log.debug("get staff rights from redis:" + staffId);
                    return allList.stream().map(item -> JSONObject.parseObject(StringUtil.toString(item), RightsExt.class)).collect(Collectors.toList());
                }
            }

            List<RightsExt> rightsList;
            List<String> rightsIds = getAllRightsIdsByStaffId(staffId);

            if (StringUtil.isNullOrEmpty(rightsIds)) {
                return null;
            }


            RightsSearchExt rightsSearch = RightsSearchExt.getInstance();
            rightsSearch.setIdIn(rightsIds);
            rightsSearch.setOrderBy(Rights.SORT_NUM);
            rightsSearch.setOrderDesc(BaseSearch.ASC_ORDER);

            rightsList = rightsService.getAllList(rightsSearch);

            clearRightsByStaffId(staffId);

            if (StringUtil.isNotObjEmpty(rightsList)) {
                rightsList.stream().forEach(rightsExt -> {
                    redisUtil.lSet(staffId, JSONObject.toJSONString(rightsExt));
                });
            }
          /*  else {//说明把权限全关了
                clearRightsByStaffId(staffId);
            }*/

            return rightsList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除某一个人的缓存权限
     *
     * @param staffId
     */
    @Override
    public void clearRightsByStaffId(String staffId) {

        log.debug("clear staff rights " + staffId);
        if (StringUtil.isNullOrEmpty(staffId)) {
            return;
        }

        try {
            redisUtil.lRemoveAll(staffId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }


    }

}